<?php

/*
 * curl请求函数
 *
 * $url String 请求地址
 * $post Array 请求参数
 *
 * return String 请求结果
 */
function curlRequest($url,$post)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2      .0.50727)");
    if($post){
        curl_setopt($ch, CURLOPT_POST, 1); // 启用POST提交  
            $new=array();
        foreach($post as $key=>$val){
            $new[] =urlencode($key).'='.urlencode($val);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, implode('&',$new));
    }
    $rst = curl_exec($ch);
    curl_close($ch);
    return $rst;
}

/*
 * 获取用户IP地址
 */
function getFromIp()
{
    $ip = "";
    if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]) 
    { 
        $ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]; 
    } 
    elseif ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"]) 
    { 
        $ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"]; 
    }
    elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"]) 
    { 
        $ip = $HTTP_SERVER_VARS["REMOTE_ADDR"]; 
    } 
    elseif (getenv("HTTP_X_FORWARDED_FOR")) 
    { 
        $ip = getenv("HTTP_X_FORWARDED_FOR"); 
    } 
    elseif (getenv("HTTP_CLIENT_IP")) 
    { 
        $ip = getenv("HTTP_CLIENT_IP"); 
    } 
    elseif (getenv("REMOTE_ADDR"))
    { 
        $ip = getenv("REMOTE_ADDR"); 
    }
    return $ip;
}
/*
 * 有效时间验证
 */
function checkActiveTime($active_time, &$msg)
{
    // 不能大于当前时间、有效期为15分钟
    if ($active_time > time() ||
        (time() - $active_time) > 900)
    {
        $msg = "检查超时";
        return false;
    }

    return true;
}

/*
 * 签名验证 $sign = md5 (bid#active_time#cp_key);
 */
function checkSign($data, &$msg)
{
    $sign_check = $data['bid'];
    $sign_check .= '#'.$data['active_time'];
    $sign_check .= '#'.CPS360_CP_KEY;
    $sign_check = md5($sign_check);
    if ($data['sign'] != $sign_check)
    {   
        $msg = "签名验证失败";
        return false;
    }

    return true;
}

/*
 * 返回错误信息
 */
function processError($msg)
{
    Header("Content-type: text/html; charset=utf-8");
    echo $msg;
}

/*
 * 返回xml数据
 */
function getXml($fields, $list)
{
    $xml = '<?xml version="1.0" encoding="utf-8"?><orders>';

    foreach ($list as $row) {
        $xml .= '<order>';

        foreach ($fields as $field) {
            $xml .= '<' . $field . '>' . htmlspecialchars($row[$field]) . '</' . $field . '>';
        }   

        $xml .= '</order>';
    }   
    $xml .= '</orders>';
    return $xml;
}   
?>
